﻿using LiteDB;
using Microsoft.Extensions.DependencyInjection;
using NordPixel.WPF.UnitOfWork.LiteDb.Core;
using System.Collections.Concurrent;

namespace NordPixel.WPF.UnitOfWork.LiteDb.Support;

public static class Extensions
{
    public static IServiceCollection AddUnitWork( this IServiceCollection services, Action<Options>? options = null )
    {
        var uowOptions = new Options();
        options?.Invoke( uowOptions );

        var contexts = new ConcurrentDictionary<string, LiteDBContext>();
        foreach (var conn in uowOptions.Connections)
        {
            var db = new LiteDatabase( conn.ConnectionString );
            contexts.TryAdd( conn.Name, new LiteDBContext( conn.Name, db ) );
        }

        services.AddSingleton( contexts );
        services.AddScoped<UnitWork>();

        return services;
    }

    public static ConcurrentDictionary<string, LiteDBContext> BuildDbContext( Action<Options>? options = null )
    {
        var uowOptions = new Options();
        options?.Invoke( uowOptions );

        var contexts = new ConcurrentDictionary<string, LiteDBContext>();
        foreach (var conn in uowOptions.Connections)
        {
            var db = new LiteDatabase( conn.ConnectionString );
            contexts.TryAdd( conn.Name, new LiteDBContext( conn.Name, db ) );
        }

        return contexts;
    }
}
